﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Diagnostics;
using Report.Properties;
using System.IO;

namespace Report
{
    public class GomezService
    {
        CookieContainer cookieContainer = new CookieContainer();
        
        public void Configure()
        {
            ServicePointManager.Expect100Continue = false;
        }

        public bool Login()
        {
            Dictionary<string, string> parameter = new Dictionary<string, string>();
            parameter.Add("action", "login");
            parameter.Add("form_string", "");
            parameter.Add("pwd", Settings.Default.PassWord);
            parameter.Add("query_string", "");
            parameter.Add("server_string", "");
            parameter.Add("url_string", "");
            parameter.Add("username", Settings.Default.User);

            HttpWebRequest webRequest = ConfigWebRequest(Settings.Default.LoginUrl, parameter, true);

            string responsetext = ExecuteRequest(webRequest);

            return true;
        }

        protected string ExecuteRequest(HttpWebRequest webRequest)
        {
            try
            {
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    int contentLength = (int)response.ContentLength;
                    byte[] buffer=new byte[contentLength];

                    Stream stream= response.GetResponseStream();
                    int readed = 0;
                    while (readed < contentLength)
                    {
                        int len = stream.Read(buffer, readed, contentLength-readed);
                        if (len == 0) break;
                        readed += len;

                    }
                    stream.Close();
                    if("gzip".Equals(response.ContentEncoding,StringComparison.CurrentCultureIgnoreCase))
                    {
                        buffer=CompressUtility.GzipDeCompress(buffer);
                    }
                    if ("deflate".Equals(response.ContentEncoding, StringComparison.CurrentCultureIgnoreCase))
                    {
                        buffer = CompressUtility.DeflateDeCompress(buffer);
                    }
                    return Encoding.UTF8.GetString(buffer);
                }
                return string.Empty;
            }
            catch (Exception e)
            {
                return string.Empty;
            }
        }

        protected HttpWebRequest ConfigWebRequest(string url, Dictionary<string, string> parameter, bool post)
        {
            string data=null;
            if (parameter != null)
            {
                StringBuilder parameterBuilder = new StringBuilder();
                foreach (KeyValuePair<string, string> keypair in parameter)
                {
                    parameterBuilder.AppendFormat("{0}={1}&", keypair.Key, keypair.Value);
                }
                data = parameterBuilder.ToString().TrimEnd('&');
                if (!post)
                {
                    url = url + "?" + data;
                }
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.CookieContainer = cookieContainer;
            request.UserAgent = Settings.Default.UserAgent;
            request.Accept = "text/html,application/xhtml+xml,application/xml,*/*;";
            request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            request.Method = post ? "POST" : "GET";

            if (post&& !string.IsNullOrEmpty(data))
            {
                request.ContentType = "application/x-www-form-urlencoded";
                byte[] binaryData=Encoding.UTF8.GetBytes(data);
                request.GetRequestStream().Write(binaryData, 0, binaryData.Length);
                request.GetRequestStream().Close();
            }

            return request;
        }
    }
}
